package com.jiexin.common;

import com.jiexin.model.SysUser;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Jay_Liu
 * @Description: 放在ThreadLocal中的对象，会被单进程执行，防止出现并发问题
 * 1.介绍：ThreadLocal相当于一个map：{key-value} 每个单独不会互相有影响的线程->线程中的对象
 * @Date: Created in 16:22 2018/4/7 0007
 * @Modified By:
 */
public class RequestHolder {

    private static final ThreadLocal<SysUser> userHolder = new ThreadLocal<SysUser>();

    private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>();

    //向ThreadLocal放入对象
    public static void add(SysUser sysUser) {
        userHolder.set(sysUser);
    }

    //向ThreadLocal放入对象
    public static void add(HttpServletRequest request) {
        requestHolder.set(request);
    }

    //从ThreadLocal中取对象
    public static SysUser getCurrentUser() {
        return userHolder.get();
    }

    public static HttpServletRequest getCurrentRequest() {
        return requestHolder.get();
    }

    //进程结束，移除对象操作，防止内存泄露
    public static void remove() {
        userHolder.remove();
        requestHolder.remove();
    }
}